"""
项目：Ai-Engineer自适应工程设计自动化插件
作者：刘昊轩、李佳音、刘伟伟、杨明久（排序不分先后）
©版权保护
"""
# src/ai_integration/fallback_client.py
import logging
from ai_integration.deepseek_client import OfficialDeepSeekClient
from ai_integration.deepseek_client_ollama import OllamaClient, ServiceUnavailableError, ModelNotFoundError


class FallbackAIClient:
    """带自动故障转移的AI客户端"""

    def __init__(self):
        self.primary_client = OllamaClient()
        self.fallback_client = OfficialDeepSeekClient()
        self.logger = logging.getLogger("FallbackClient")

        self.failure_count = 0
        self.max_failures = 3

    def generate(self, prompt: str) -> str:
        """带自动回退的生成方法"""
        try:
            if self.failure_count >= self.max_failures:
                self.logger.warning("主服务已连续失败，直接使用备用服务")
                return self._use_fallback(prompt)

            response = self.primary_client.generate(prompt)
            self._reset_counter()
            return response

        except (ServiceUnavailableError, ModelNotFoundError) as e:
            self.failure_count += 1
            self.logger.error(f"主服务失败（{self.failure_count}/{self.max_failures}）: {str(e)}")
            return self._use_fallback(prompt)

    def _use_fallback(self, prompt: str) -> str:
        """使用备用服务"""
        try:
            self.logger.warning("正在切换至备用服务...")
            return self.fallback_client.generate(prompt)
        except Exception as e:
            self.logger.critical("所有服务均不可用")
            raise RuntimeError(f"所有AI服务不可用: {str(e)}")

    def _reset_counter(self):
        """重置失败计数器"""
        if self.failure_count > 0:
            self.logger.info("主服务恢复，重置失败计数器")
            self.failure_count = 0